﻿using Corina.Datamodel.DataObject;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Corina.Datamodel.Entities;
using Corina.Enumerations;
using Corina.DataContext.Service;
using System.Data;

namespace Corina.DataContext.Master
{
    public class DeviceMaster : MasterBase
    {
        public ResultInfo GetFetchedItems(string deviceSn, int index, int size, int saleFlag, int kind = 0)
        {
            int count = 0;
            DataTable table = GetInstance<DeviceService>().GetFetchedItems(ConnectionString(DatabaseKeys.CORINA_PROD), kind, deviceSn, saleFlag, index, size, ref count);
            string[] columns = table.Columns.OfType<DataColumn>().Select(t => t.ColumnName).ToArray();

            var items = (from t in table.AsEnumerable()
                         select new DataObjectInfo()
                         {
                             Values = GetObjectOfValue(t, columns)
                         });
            ResultInfo result = new ResultInfo(ResultValue.Succeed);
            result.DataObjects.AddRange(items);
            result.TotalCount = count;
            return result;
        }

        public ResultInfo GetUserOwnDevice(string account, string password, int kind, string deviceSn, int index, int size)
        {
            ResultValue resultValue = VerifyAccount<UserInfo>(account, password);
            ResultInfo result = new ResultInfo(resultValue);
            if (resultValue == ResultValue.Succeed)
            {
                int userId = GetAccountInfo<UserInfo>(account).Id;

                int count = 0;
                DataTable table = GetInstance<DeviceService>().GetUsersDevice(ConnectionString(DatabaseKeys.CORINA_PROD), userId, kind, deviceSn, index, size, ref count);
                string[] columns = table.Columns.OfType<DataColumn>().Select(t => t.ColumnName).ToArray();

                var items = (from t in table.AsEnumerable()
                             select new DataObjectInfo()
                             {
                                 Values = GetObjectOfValue(t, columns)
                             });
                result.DataObjects.AddRange(items);
                result.TotalCount = count;
            }
            return result;
        }

        public ResultInfo Update(string account, string password, DeviceInfo entity, EntityOperation operation)
        {
            ResultValue resultValue = VerifyAccount<ManagerInfo>(account, password);

            if (resultValue == ResultValue.Succeed)
            {
                bool flag = GetInstance<DeviceService>().Update(ConnectionString(DatabaseKeys.CORINA_PROD), entity, operation);
                if (!flag)
                {
                    resultValue = ResultValue.Failed;
                }
            }

            return new ResultInfo(resultValue);
        }
    }
}
